﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Kugar.Core.ExtMethod;

namespace Kugar.Core.Network
{
    /// <summary>
    /// Description of RequestEx.
    /// </summary>
    public static class WebHelper
    {
        /// <summary>
        /// 	获取指定Uri返回的文本数据
        /// </summary>
        /// <param name="uri">远程地址</param>
        /// <param name="encoding">文本编码</param>
        /// <returns></returns>
        public static string GetUriData(string uri, System.Text.Encoding encoding=null)
        {
            var request = (HttpWebRequest) HttpWebRequest.Create(uri);
            request.Method = "get";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept =
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/msword, */*";
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
            //request.CachePolicy=new System.Net.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);	
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");

            HttpWebResponse resp = null;
            System.IO.Stream respStream = null;
            try
            {
                resp = (HttpWebResponse) request.GetResponse();

                using (respStream = resp.GetResponseStream())
                {
                    if (encoding==null)
                    {
                        if (!string.IsNullOrWhiteSpace(resp.ContentEncoding))
                        {
                            encoding =Encoding.GetEncoding(resp.ContentEncoding);
                        }
                        else if (!string.IsNullOrWhiteSpace(resp.CharacterSet))
                        {
                            encoding = Encoding.GetEncoding(resp.CharacterSet);
                        }
                        else
                        {
                            var reader = new StreamReader(respStream, Encoding.ASCII);

                            string html = reader.ReadToEnd();

                            if (reg_charset.IsMatch(html))
                            {
                                encoding= Encoding.GetEncoding(reg_charset.Match(html).Groups["charset"].Value);
                            }
                        }
                    }

                    if (encoding==null)
                    {
                        encoding = Encoding.Default;
                    }



                    if (resp.ContentEncoding.Contains("gzip"))
                    {
                        return getGzipStr(respStream, encoding);
                    }
                    else if (resp.ContentEncoding.Contains("deflate"))
                    {
                        return getDeflateStr(respStream, encoding);
                    }
                    else
                    {
                        return getNormal(respStream, encoding);
                    }
                }

            }
            catch (Exception)
            {
                return string.Empty;
            }
            finally
            {
                if (respStream != null)
                {
                    respStream.Close();
                    respStream.Dispose();
                }

                if (resp != null)
                {
                    resp.Close();
                }

            }
        }

        public static string GetUriDataByPost(string uri, Dictionary<string, string> postDatas,
            System.Text.Encoding encoding = null)
        {
            var request = (HttpWebRequest) HttpWebRequest.Create(uri);
            request.Method = "post";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept =
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/msword, */*";
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
            request.ContentType = "application/x-www-form-urlencoded";
            //request.CachePolicy=new System.Net.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);	
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");

            StringBuilder dataStr = new StringBuilder();

            foreach (var data in postDatas)
            {
                dataStr.AppendFormat("{0}={1}&",data.Key, Uri.EscapeUriString(data.Value));
            }

            using (var requestStream = request.GetRequestStream())
            {
                var bytes = Encoding.UTF8.GetBytes(dataStr.ToString().Trim());
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }

            HttpWebResponse resp = null;
            Stream respStream = null;
            try
            {
                resp = (HttpWebResponse) request.GetResponse();

                using (respStream = resp.GetResponseStream())
                {
                    if (encoding == null)
                    {
                        if (!string.IsNullOrWhiteSpace(resp.ContentEncoding))
                        {
                            encoding = Encoding.GetEncoding(resp.ContentEncoding);
                        }
                        else if (!string.IsNullOrWhiteSpace(resp.CharacterSet))
                        {
                            encoding = Encoding.GetEncoding(resp.CharacterSet);
                        }
                        else
                        {
                            var reader = new StreamReader(respStream, Encoding.ASCII);

                            string html = reader.ReadToEnd();

                            if (reg_charset.IsMatch(html))
                            {
                                encoding = Encoding.GetEncoding(reg_charset.Match(html).Groups["charset"].Value);
                            }
                        }
                    }

                    if (encoding == null)
                    {
                        encoding = Encoding.Default;
                    }

                    if (resp.ContentEncoding.Contains("gzip"))
                    {
                        return getGzipStr(respStream, encoding);
                    }
                    else if (resp.ContentEncoding.Contains("deflate"))
                    {
                        return getDeflateStr(respStream, encoding);
                    }
                    else
                    {
                        return getNormal(respStream, encoding);
                    }

                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
            finally
            {
                if (respStream != null)
                {
                    respStream.Close();
                    respStream.Dispose();
                }

                if (resp != null)
                {
                    resp.Close();
                }
            }
        }

        public static WebDownloadFileInfo GetFile(Uri uri)
        {
            var request = (HttpWebRequest) WebRequest.Create(uri);

            request.Method = "get";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.UserAgent =
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("Accept-Encoding", "gzip,deflate");

            HttpWebResponse resp = null;
            System.IO.Stream respStream = null;
            try
            {
                resp = (HttpWebResponse) request.GetResponse();

                if ((int) resp.StatusCode != 200)
                {
                    return null;
                }

                var item = new WebDownloadFileInfo();

                if (!string.IsNullOrWhiteSpace(resp.ContentType))
                {
                    var extLst = resp.ContentType.Split('/');
                    if (extLst.Length == 2)
                    {
                        item.FileExt = extLst[1];
                    }
                }

                if (resp.ContentLength > 0)
                {
                    item.FileSize = (int) resp.ContentLength;
                }

                using (respStream = resp.GetResponseStream())
                {
                    item.Data = respStream.ReadAllBytes();
                }

                return item;

            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (respStream != null)
                {
                    respStream.Close();
                    respStream.Dispose();
                }

                if (resp != null)
                {
                    resp.Close();
                }

            }
        }

        public static WebDownloadFileInfo GetFile(string uri)
        {
            return GetFile(uri.ToUri());
        }



        public class WebDownloadFileInfo
        {
            public string FileExt { set; get; }
            public int FileSize { set; get; }
            public byte[] Data { set; get; }
        }

        private static string getGzipStr(Stream srcStream, System.Text.Encoding encoding)
        {

            using (GZipStream zipStream = new GZipStream(srcStream, CompressionMode.Decompress))
            using (StreamReader responeReader = new StreamReader(zipStream, encoding))
            {
                var data = responeReader.ReadToEnd();

                return data;
            }
        }

        private static string getDeflateStr(Stream srcStream, System.Text.Encoding encoding)
        {
            using (DeflateStream zipStream = new DeflateStream(srcStream, CompressionMode.Decompress))
            using (StreamReader responeReader = new StreamReader(zipStream, encoding))
            {
                var data = responeReader.ReadToEnd();

                return data;
            }
        }

        private static string getNormal(Stream srcStream, System.Text.Encoding encoding)
        {
            var data = srcStream.ReadToEnd(encoding);

            return data;
        }

        private static readonly Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");

        private static string getEncodingData(HttpWebResponse response)
        {
            StreamReader reader = null;
            try
            {
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        reader =new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                    else
                        reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);

                    string html = reader.ReadToEnd();

                    if (reg_charset.IsMatch(html))
                    {
                        return reg_charset.Match(html).Groups["charset"].Value;
                    }
                    else if (response.CharacterSet != string.Empty)
                    {
                        return response.CharacterSet;
                    }
                    else
                    {
                        return Encoding.Default.BodyName;
                    }
                        
                
            }
            catch
            {
                return Encoding.Default.BodyName;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (reader != null)
                    reader.Close();
            }
        }
    }
}
